package com.easyban.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easyban.common.BaseContext;
import com.easyban.common.R;
import com.easyban.dto.UserDto;
import com.easyban.entity.User;
import com.easyban.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 登录
     *
     * @param request
     * @param user
     * @return
     */
    @PostMapping("/login")
    public R<User> login(HttpServletRequest request, @RequestBody User user) {
        //1.将页面提交的密码password进行md5加密处理
        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2.根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserId, user.getUserId());
        User result = userService.getOne(queryWrapper);

        //3.如果没有查询到则返回登录失败结果
        if (result == null) return R.error("登陆失败");

        //4.密码比对，如果不一致则返回登陆失败结果
        if (!result.getPassword().equals(password)) return R.error("登陆失败");

        //6.登陆成功，将员工id，status存入Session并返回登陆成功结果
        request.getSession().setAttribute("user", result.getId());
        request.getSession().setAttribute("status", result.getStatus());

       /* User u = new User();
        u.setId(result.getId());
        u.setUserId(result.getUserId());
        u.setUsername(result.getUsername());
        u.setMobile(result.getMobile());*/

        return R.success(result);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        request.getSession().removeAttribute("status");
        return R.success("成功注销！");
    }

    /**
     * 注册
     *
     * @param userDto
     * @return
     */
    @PostMapping("/reg")
    public R<String> save(@RequestBody UserDto userDto) {
        log.info("用户注册：{}", userDto.toString());

        userDto.setPassword(DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes()));
        userService.saveUserDto(userDto);

        return R.success("注册成功");
    }

    /**
     * 伪获取状态
     * @param request
     * @return
     */
    @GetMapping("/getStatus")
    public R<String> getStatus(HttpServletRequest request) {
        if (BaseContext.getCurrentId() == null) {
            return R.error("未登录");
        }
        return R.success("正在获取状态...");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<User>> Page(int page, int pageSize, String name) {
        log.info("执行分页查询....");
        //构造分页构造器
        Page<User> pageInfo = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        if (StringUtils.isNoneEmpty(name)) {
            queryWrapper.like(User::getUserId, name)
                    .or().like(User::getUsername, name)
                    .or().like(User::getSex, name)
                    .or().like(User::getEmail, name)
                    .or().like(User::getMobile, name);
        }
        //添加排序条件
        queryWrapper.orderByDesc(User::getUserId);

        //执行查询
        userService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    @GetMapping("/{id}")
    public R<UserDto> getUserById(@PathVariable Long id) {

        UserDto user = userService.getOnes(id);
        return R.success(user);
    }

    @PutMapping("/{id}")
    public R<String> update(@PathVariable Long id, @RequestBody UserDto userDto) {

        userService.updateUser(userDto);

        return R.success("修改成功");
    }
    @DeleteMapping("/del/{id}")
    public R<String> delete(@PathVariable Long id) {
        userService.removeUser(id);
        return R.success("删除成功");
    }
}
